

import React, {Component} from 'react';
import {Platform, StyleSheet, View, NetInfo, Button, PermissionsAndroid, NativeModules} from 'react-native';

import {AudioRecorder, AudioUtils} from 'react-native-audio';
import Sound from 'react-native-sound'; // 播放声音组件

import Video from 'react-native-video'; // 播放声音组件

const Manager = NativeModules.PlayingViewController;

Manager.viewDidLoad();



const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
  android:
    'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});



type Props = {};
export default class App extends Component<Props> {

  constructor(props) {
    super(props);
    this.prepareRecordingPath = this.prepareRecordingPath.bind(this);     //执行录音的方法
    this.checkPermission = this.checkPermission.bind(this);               //检测是否授权
    this.record = this.record.bind(this);                                 //录音
    this.stop = this.stop.bind(this);                                     //停止
    this.play = this.play.bind(this);                                     //播放
    this.pause = this.pause.bind(this);                                   //暂停
    this.finishRecording = this.finishRecording.bind(this);
    this.state = {
      ssid: '',
      bssid: '',
      ssidArray: [],
      currentTime: 0.0, //开始录音到现在的持续时间
      recording: false, //是否正在录音
      stoppedRecording: false, //是否停止了录音
      finished: false, //是否完成录音
      audioPath: AudioUtils.DocumentDirectoryPath + '/androidtest.aac', //路径下的文件名
      hasPermission: undefined, //是否获取权限
      pause: true
    }
  }

  componentDidMount() {
    // 页面加载完成后获取权限
    this.checkPermission().then((hasPermission) => {
      this.setState({ hasPermission });

      //如果未授权, 则执行下面的代码
      if (!hasPermission) return;
      this.prepareRecordingPath(this.state.audioPath);

      AudioRecorder.onProgress = (data) => {
        this.setState({currentTime: Math.floor(data.currentTime)});
      };

      AudioRecorder.onFinished = (data) => {
        if (Platform.OS === 'ios') {
          this.finishRecording(data.status === "OK", data.audioFileURL);
        }
      };

    })
    
  }
  

  prepareRecordingPath(audioPath) {
    AudioRecorder.prepareRecordingAtPath(audioPath, {
      SampleRate: 22050,
      Channels: 1,
      AudioQuality: "Low", //录音质量
      AudioEncoding: "aac", //录音格式
      AudioEncodingBitRate: 32000 //比特率
    });
  }

  checkPermission() {
    if (Platform.OS !== 'android') {
      return Promise.resolve(true);
    }
    const rationale = {
      'title': '获取录音权限',
      'message': 'XXX正请求获取麦克风权限用于录音,是否准许'
    };
    
    return requestCameraPermission();

    async function requestCameraPermission() {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
          rationale
        )
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log("You can use the RECORD_AUDIO")
          return PermissionsAndroid.RESULTS.GRANTED;
        } else {
          console.log("RECORD_AUDIO permission denied")
        }
      } catch (err) {
        console.warn(err)
      }
    }
  }
  

  async record() {
    // 如果正在录音
    if (this.state.recording) {
      alert('正在录音中!');
      return;
    }
    //如果没有获取权限
    if (!this.state.hasPermission) {
      alert('没有获取录音权限!');
      return;
    }

    alert('开始录音!');

    //如果暂停获取停止了录音
    if(this.state.stoppedRecording){
      this.prepareRecordingPath(this.state.audioPath);
    }

    this.setState({recording: true});

    try {
      const filePath = await AudioRecorder.startRecording();
    } catch (error) {
      console.error(error);
    }
    
  }

  async stop() {
    // 如果没有在录音
    if (!this.state.recording) {
    alert('没有录音, 无需停止!');
    return;
    }
    
    this.setState({stoppedRecording: true, recording: false});
    
    try {
      const filePath = await AudioRecorder.stopRecording();
    
      if (Platform.OS === 'android') {
        this.finishRecording(true, filePath);
      }
      return filePath;
    } catch (error) {
      console.error(error);
    }
  }

  async play() {
    // 如果在录音 , 执行停止按钮
    if (this.state.recording) {
    await this.stop();
    }
    
    // 使用 setTimeout 是因为, 为避免发生一些问题 react-native-sound中
    setTimeout(() => {
      // var sound = new Sound(this.state.audioPath, '', (error) => {
      //   if (error) {
      //     console.log('failed to load the sound', error);
      //   }
      //   console.log('duration in seconds: ' + sound.getDuration() + 'number of channels: ' + sound.getNumberOfChannels());
      //   alert('开始播放');
      // });

      // setTimeout(() => {
      //   sound.play((success) => {
      //     if (success) {
      //       alert('播放完成');
      //       console.log('successfully finished playing');
      //     } else {
      //       console.log('playback failed due to audio decoding errors');
      //     }
      //   });
      // }, 100);

      var sound = new Sound('http://fs.w.kugou.com/201812051401/458fdc8d26ebff3c921791261bc94ef7/G083/M07/1E/10/M5QEAFgvQgWATvYEAEBvKnQO8lk294.mp3', null, (error) => {
        if (error) {
          console.log('failed to load the sound', error);
        }
        console.log('duration in seconds: ' + sound.getDuration() + 'number of channels: ' + sound.getNumberOfChannels());
        alert('开始播放');
        sound.play((success) => {
          if (success) {
            alert('播放完成');
            console.log('successfully finished playing');
          } else {
            console.log('playback failed due to audio decoding errors');
          }
        });
      });

      // Manager.setupLockScreenInfo('123', '234');
      // Manager.createRemoteCommandCenter((data) => {
      //   alert(data);
      //   // if (data == '暂停') {
      //   //   sound.pause();
      //   // } else {
      //   //   sound.play();
      //   // }
      //   // Manager.setupLockScreenInfo('456', '567');
      // });
      console.log(sound);
    
      
    }, 100);
  }


  async pause() {
    if (!this.state.recording) {
    alert('没有录音, 无需停止!');
    return;
    }
    
    this.setState({stoppedRecording: true, recording: false});
  
    try {
      const filePath = await AudioRecorder.pauseRecording();
  
      // 在安卓中, 暂停就等于停止
      if (Platform.OS === 'android') {
        this.finishRecording(true, filePath);
      }
    } catch (error) {
      console.error(error);
    }
  }

  finishRecording(didSucceed, filePath) {
    this.setState({ finished: didSucceed });
    console.log('Finished recording of duration');
  }



  

  render() {
    
    return (
      <View style={styles.container}>
        <Button
          onPress={this.record}
          title="录音"
          color="#841584"
          accessibilityLabel="Learn more about this purple button"
        />
        <Button
          onPress={this.stop}
          title="停止录音"
          color="#841584"
          accessibilityLabel="Learn more about this purple button"
        />
        <Button
          onPress={this.pause}
          title="暂停录音"
          color="#841584"
          accessibilityLabel="Learn more about this purple button"
        />
        <Button
          onPress={this.play}
          title="播放录音"
          color="#841584"
          accessibilityLabel="Learn more about this purple button"
        />
        <Video
          source={{uri: 'http://fs.w.kugou.com/201812051401/458fdc8d26ebff3c921791261bc94ef7/G083/M07/1E/10/M5QEAFgvQgWATvYEAEBvKnQO8lk294.mp3'}}
          ref='video'
          // rate={1}
          volume={1.0}
          paused={this.state.pause}
          onProgress={(e) => {}}
          onLoad={(e) => {}} />
        <Button
          onPress={() => {this.setState({pause: !this.state.pause})}}
          title="播放video"
          color="#841584"
          accessibilityLabel="Learn more about this purple button"
        />
        <Button
          onPress={() => {this.setState({pause: !this.state.pause})}}
          title="暂停video"
          color="#841584"
          accessibilityLabel="Learn more about this purple button"
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
